package com.ray.validate.support.rule;

import com.ray.validate.support.utils.PropertyUtils;
import com.ray.validate.support.utils.ValidateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import javax.validation.constraints.Pattern;

/**
 * @author bo shen
 * @Description: 正则表达式
 * @Class: PatternRule
 * @Package tf56.antcolonyums.validate.support.rule
 * @date 2019/11/19 16:56
 * @company <p>杭州传化陆鲸科技有限公司</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Slf4j
public class PatternRule implements Rule<Pattern> {

    @Override
    public void rule(Object bean, String fieleName, Pattern conditionRegular) {
        if (!ObjectUtils.isEmpty(conditionRegular)) {
            ValidateUtil.hasLength(conditionRegular.regexp(), conditionRegular.message());
            Object objectValue = PropertyUtils.getProperty(bean,fieleName);
            if (objectValue != null) {
                log.info("正则表达式校验值:{}", objectValue);
                ValidateUtil.isTrue(String.valueOf(objectValue).matches(conditionRegular.regexp()), conditionRegular.message());
            }
        }
    }

    @Override
    public void rule(Object value, Pattern conditionRegular) {
        ValidateUtil.hasLength(conditionRegular.regexp(), conditionRegular.message());
        if (value != null) {
            log.info("正则表达式校验值:{}", value);
            ValidateUtil.isTrue(String.valueOf(value).matches(conditionRegular.regexp()), conditionRegular.message());
        }
    }
}
